package com.gin.kotlin.gf2gamecommunity.composable

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.offset
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Email
import androidx.compose.material3.Badge
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.gin.kotlin.gf2gamecommunity.routes.MessageListRoute
import com.gin.kotlin.gf2gamecommunity.viewmodel.MessageViewModel

/**
 * 提醒消息Icon按钮
 * @param onNavigateToMessageList (route: MessageListRoute) -> Unit
 * @param messageViewModel MessageViewModel
 * @param modifier Modifier
 */
@Composable
fun MessageIconButton(
    onNavigateToMessageList: (route: MessageListRoute) -> Unit,
    messageViewModel: MessageViewModel = viewModel(),
    modifier: Modifier = Modifier
) {
    val unreadCountState = messageViewModel.unreadCount.fetch().observeAsState()
    IconButton(onClick = { onNavigateToMessageList(MessageListRoute()) }) {
        Box(contentAlignment = Alignment.TopEnd) {
            Icon(imageVector = Icons.Filled.Email, contentDescription = "消息")
            // 红点
            unreadCountState.value?.total()
                ?.takeIf { it > 0 }
                ?.let { Badge(modifier = Modifier.offset(4.dp, (-4).dp)) { Text(it.toString()) } }
        }
    }
}